import os, logging
from google.appengine.dist            import use_library
use_library('django', '1.2')

from google.appengine.ext.webapp      import template
from google.appengine.ext             import webapp
from google.appengine.api             import urlfetch
from google.appengine.ext.webapp.util import run_wsgi_app

from app_settings import *
from facebook_sdk import Facebook

ROOT_PATH = os.path.dirname(__file__)
TEMPLATE = os.path.join(ROOT_PATH, 'templates')
template_values = {
        'app_id'      : app_id,
        'host_url'    : host_url,
        'first'       : first,
        'invhead'     : invhead,
        'invmsg'      : invmsg,
        'forcehead'   : forcehead,
        'forcebefore' : forcebefore,
        'forceafter'  : forceafter,
        'invreq'      : invreq,
        'content'     : content,
        }

class MainPage(webapp.RequestHandler):
    def get(self):
        path = os.path.join(TEMPLATE, 'index.html')
        self.response.out.write(template.render(path, template_values))

    def post(self):
        request_ids = self.request.get('request_ids', '')
        signed_request = self.request.get('signed_request', '')
        path = os.path.join(TEMPLATE, 'index.html')
        if request_ids:
            if signed_request:
                fb = Facebook(app_id = app_id, app_secret=app_secret)
                fb.load_signed_request(signed_request)
                try:
                    app_requests = fb.api(u'/me/apprequests')
                except:
                    pass
                else:
                    try:
                        data = app_requests.get(u'data')[0]
                    except:
                        pass
                    else:
                        del_req = data.get(u'id','')
                        del_to  = data.get(u'to','').get(u'id')
                        del_id  = u'%s_%s' % (del_req, del_to)
                        if del_id:
                            del_url = 'https://graph.facebook.com/%s?access_token=%s&method=delete' % (del_id, fb.access_token)
                            try:
                                logging.info("Try to fetch [%s]" % del_url)
                                urlfetch.fetch(del_url)
                            except:
                                pass

                self.response.out.write(template.render(path, template_values))
        elif signed_request:
            self.response.out.write(template.render(path, template_values))
        else:
            self.response.out.write('<script>top.location = "%s";</script>' % fan_page_url)

class channel(webapp.RequestHandler):
    def get(self):
        path = os.path.join(TEMPLATE, 'channel.html')
        self.response.out.write(template.render(path, {}))

application = webapp.WSGIApplication([
    ('/', MainPage),
    ('/channel.html', channel)], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
